package com.qf.votesystem.entity.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.votesystem.Contants.Constants;
import com.qf.votesystem.entity.entity.Phonename;
import com.qf.votesystem.entity.mapper.PhonenameMapper;
import com.qf.votesystem.entity.service.IPhonenameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.votesystem.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CM
 * @since 2023-02-24
 */
@Service
public class PhonenameServiceImpl extends ServiceImpl<PhonenameMapper, Phonename> implements IPhonenameService {


    /**
     * 给明星投票
     * @param phoneNum
     * @param username
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo vote(String phoneNum, String username, HttpServletRequest request) {
        //从请求头中获取token
        String token = request.getHeader("voteToken"+phoneNum);

        //如果请求头中没有携带token 则直接拒绝请求
        if(token == null || "".equals(token)){
            //
            return ResultVo.error("未带请求头token");
        }

        boolean validate = JWT.of(token).setKey(Constants.SALT.getBytes(StandardCharsets.UTF_8)).validate(0);

        if(validate){

            //1.获取当前投票的手机号,检查数据库中的手机号码是否有过该手机号码的投票

            Phonename votePhone = getOne(new QueryWrapper<Phonename>().eq("phonenum", phoneNum));

            if(votePhone != null){
                //2.检查超时（一分钟）,获取投票时间

                long time = votePhone.getVotetime().getTime();

                //2.1获取当前时间

                long now = System.currentTimeMillis();

                if((now - time) > 60000){

                    //3.如果超时则返回错误消息

                    return ResultVo.error("一个手机号每分钟只能投票一次！");

                }else {

                    //4.如果不超时就继续投票
                    voteTicket(phoneNum,username);
                }

            }else {

                //投票
                voteTicket(phoneNum,username);
            }
            return ResultVo.ok();
        }else {
            return ResultVo.error("salt error");
        }
    }

    /**
     * 统计投票数量并且返回统计投票信息
     * @return
     */
    @Override
    public Map<String, Integer> countTickets() {

        //查询投票结果表
        //1.查询语句 SELECT starname,COUNT(*) tickets FROM phonename GROUP BY starname

        List<Phonename> list = list(new QueryWrapper<Phonename>().select("starname,COUNT(*) as tickets").groupBy("starname"));

        //2.将 List<Phonename> --> Map<name,ticket>

        Map<String, Integer> voteCount = list.stream().collect(Collectors.toMap(Phonename::getStarname, Phonename::getTickets));

        return voteCount;
    }

    /**
     * 投票方法
     * @param phoneNum
     * @param username
     */
    private void voteTicket(String phoneNum, String username) {

        Phonename phonename = new Phonename();

        phonename.setPhonenum(phoneNum);
        phonename.setPhonenum(username);
        phonename.setVotetime(new Date());

        save(phonename);

    }

}
